package com.lw.leetcode.bit.b;

/**
 * Created with IntelliJ IDEA.
 * bit
 * 面试题 08.05. 递归乘法
 *
 * @author liw
 * @version 1.0
 * @date 2021/9/13 11:49
 */
public class Multiply {

    public static void main(String[] args) {
        Multiply test = new Multiply();
        int a = -13;
        int b = -15;

        int multiply = test.multiply(a, b);
        System.out.println(multiply);
    }

    public int multiply(int a, int b) {
        boolean flag = true;
        if (a < 0) {
            a = (~a) + 1;
            flag = !flag;
        }
        if (b < 0) {
            b = (~b) + 1;
            flag = !flag;
        }
        int item = b;
        int sum = 0;
        while (item != 1) {
            if ((item & 1) == 1) {
                sum += a;
            }
            a <<= 1;
            item >>= 1;
        }
        sum = a + sum;
        return flag ? sum : (~sum + 1);
    }

}
